package.cpath = package.cpath .. ";/usr/lib/lua/5.1/?.so"
local sproto = require "sproto"
local core = require "sproto.core"
local print_r = require "print_r"

local sp = sproto.parse [[
.Person {
	name 0 : string
	id 1 : integer
	email 2 : string
	real 4: double

	.PhoneNumber {
		number 0 : string
		type 1 : integer
	}

	phone 3 : *PhoneNumber
}

.AddressBook {
	person 0 : *Person(id)
	others 1 : *Person(id)
}
]]

-- core.dumpproto only for debug use
core.dumpproto(sp.__cobj)

local def = sp:default "Person"
print("default table for Person")
print_r(def)
print("--------------")


local person = {
	[10000] = {
		name = "Alice",
		id = 10000,
		phone = {
			{ number = "123456789" , type = 1 },
			{ number = "87654321" , type = 2 },
		}
	},
	[20000] = {
		name = "Bob",
		id = 20000,
		phone = {
			{ number = "01234567890" , type = 3 },
		}
	}
}

local ab = {
	person = setmetatable({}, { __index = person, __pairs = function() return next, person, nil end }),
	others = {
		{
			name = "Carol",
			id = 30000,
			phone = {
				{ number = "9876543210" },
			},
			real = 1234.56789,
		},
	}
}

collectgarbage "stop"

local code = sp:encode("AddressBook", ab)
print("encode return type = " .. type(code))
local addr = sp:decode("AddressBook", code)
print("decode return type = " .. type(addr))
print_r(addr)
print("--------------")
local code2, len2 = sp:pencode2("AddressBook", ab)
print("encode2 return type = " .. type(code2) .. ", len type = " .. type(len2))
local addr2 = sp:pdecode2("AddressBook", code2, len2)
print("decode return type = " .. type(addr2))
print_r(addr2)
